package cn.eaay.stock.service.impl;

import cn.eaay.stock.service.CaptchaService;
import cn.eaay.stock.utils.IdWorker;
import cn.eaay.stock.vo.resp.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service("captchaService")
public class CaptchaServiceImpl implements CaptchaService {

    @Resource
    private IdWorker idWorker;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public R<Map> generateCaptcha() {
        // 生成4位数的验证码
        String checkCode = RandomStringUtils.randomNumeric(4);
        log.info("checkCode => {}", checkCode);
        // 生成全局唯一id，作为验证码的key
        String rKey = String.valueOf(idWorker.nextId());
        log.info("rKey => {}", rKey);
        // 将验证码存入redis，有效期为1分钟
        redisTemplate.opsForValue().set(rKey, checkCode, 60 * 2, TimeUnit.SECONDS);
        // 组装数据
        Map<String, String> map = new HashMap<>();
        map.put("code", checkCode);
        map.put("rkey", rKey);
        return R.ok(map);
    }
}
